package com.tutk.P2PCam264;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;

import com.tutk.IOTC.Camera;
import com.tutk.IOTC.IRegisterIOTCListener;
import com.tutk.IOTC.st_LanSearchInfo;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TenvisUtil implements IRegisterIOTCListener {
	private DatabaseManager dbm;
	private Handler handler_main ;
	private List<SearchResult> list_lan = new ArrayList<SearchResult>();
	private List<MyCamera> CameraList = new ArrayList<MyCamera>();
	
	private final String NAME="admin";//默认手机号
	private final String PASSWORD="admin";//默认密码
	private final int PORT=80;//默认端口
	
	private Context mContext;
	private String NickName,Uid,Pwd;
	private String oldUid;
	private String resultUID = "";
	public TenvisUtil(){}
	
	public TenvisUtil(Context ctx, Handler handler){
		mContext = ctx;
		this.handler_main = handler;
		dbm = new DatabaseManager(ctx, 9);
	}
	
	//判断是否联网
	private boolean isNetworkConnected() {
	    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo ni = cm.getActiveNetworkInfo();
	    ni.isAvailable();
	    ni.getTypeName();
	    ni.getType();
	    return ni != null && ni.isConnectedOrConnecting();
	}

	private boolean isApMode(){
		if(Uid!=null && Uid.length() == 20){
			WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			int toIP= wifiInfo.getIpAddress();
			String myIP = String.format("%d.%d.%d.%d", (toIP & 0xff), (toIP >> 8 & 0xff), (toIP >> 16 & 0xff), (toIP >> 24 & 0xff));
			Log.d("Jason","IP is "+myIP+".");
			if (myIP!=null&&myIP.startsWith("192.168.")){
				return true;
			}
		}
		return false;
	}
	
	//初始化参数
	public void setValue(String name,String uid,String pwd){
		this.NickName = name;
		this.Uid = uid;
		this.oldUid = uid;
		this.Pwd = pwd;
		this.resultUID = uid;
	}
	//查询本定mapping记录
	private String queryLocalMapping(){
		String uid = null;
		List<Map<String,String>> list = dbm.getMappingUidsByOldUid(Uid);
		if(list!=null && list.size()>0){
			Map<String, String> map = list.get(0);
			if(map!=null){
				uid = map.get("map_uid");
			}
		}
		return uid;
	}
	//返回check UID的结果给调用页面
	private void goback(){
		Message msg = handler_main.obtainMessage();
		msg.obj = resultUID+"#"+oldUid;
		msg.what = 0;
		handler_main.sendMessage(msg);
		
		for (MyCamera camera: CameraList) {
			if(camera!=null){
				camera.unregisterIOTCListener(this);
				camera.disconnect();
				camera = null;
			}
		}
	}
	
	//check UID的function
	public void exce(){
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				
//				if(Uid.length()== 20){
//					burningUidForDevice("192.168.10.119",7777,"20000000000000000025","30000000000000000025");
//					return;
//				}
//				检测是否是AP mode
				if(isApMode()){
					goback();
					return ;
				}
				//是否存在本地记录
				String localMapingUid = queryLocalMapping();
				if(localMapingUid != null){
					//存在本地记录
					resultUID = localMapingUid;
					goback();
					return;
				}
				Map<String, Object> map = checkUidInBlackList(Uid);
				int isBlack = Integer.parseInt(map.get("isBlack").toString());
				   Log.i("isBlack", String.valueOf(isBlack));
				if(isBlack == 0){
					dbm.addUidMapping(Uid, Uid, 1);
					
					goback();
				}else if(isBlack == 1){
					int cnt = Integer.parseInt(map.get("cnt").toString());
					if(cnt == 0){
						final String ip_tmp = isInLanSearchList(Uid);
						if(ip_tmp!=null && !"".equals(ip_tmp)){
							//in lan list
							getNewUidFromServer(Uid,new IGetNewUid() {
								
								@Override
								public void returnNewUid(String newUID) {
									if(newUID!=null && newUID.length() == 20){
										burningUidForDevice(ip_tmp, PORT, Uid, newUID);
									}
									goback();
								}
							});
							
						}else{
							//not in lan list
							//-----------------------game over-----------------------
							goback();
						}
					}else if(cnt == 1){
						Object uid_1_obj = map.get("uid_1");
						if(uid_1_obj!=null){
							final String uid_1_from_server = uid_1_obj.toString();
							if(uid_1_from_server!=null){
								tryConnect(NickName, uid_1_from_server, Pwd,new ConnectCallBack() {
									
									@Override
									public void connectResult(boolean successOrFail) {
										if(successOrFail){
											//success
											dbm.addUidMapping(Uid, uid_1_from_server, 1);
											
											resultUID = uid_1_from_server;
											
											goback();
										}else{
											//failed ，判断是否在lan list中
											final String ip_tmp = isInLanSearchList(Uid);
											if(ip_tmp!=null && !"".equals(ip_tmp)){
												getNewUidFromServer(Uid,new IGetNewUid() {
													
													@Override
													public void returnNewUid(String newUID) {
														if(newUID!=null && newUID.length() == 20){
															burningUidForDevice(ip_tmp, PORT, Uid, newUID);
														}
														goback();
													}
												});
												
											}else{
												//not in lan list
												//-----------------------game over-----------------------
												goback();
											}
										}
									}
								});
							}else{
								goback();
							}
						}else{
							goback();
						}
					}else if(cnt == 2){
						final Object uid_1_obj = map.get("uid_1");
						final Object uid_2_obj = map.get("uid_2");
						
						if(uid_1_obj!=null){
							final String uid_1_from_server = uid_1_obj.toString();
							if(uid_1_from_server!=null){
								tryConnect(NickName, uid_1_from_server, Pwd,new ConnectCallBack() {
									
									@Override
									public void connectResult(boolean successOrFail) {
										if(successOrFail){
											//success
											dbm.addUidMapping(Uid, uid_1_from_server, 1);
											//update device table
											dbm.updateDevUid(Uid, uid_1_from_server);
											resultUID = uid_1_from_server;
											
											goback();
										}else{
											//-----------------------game over-----------------------
//											goback();
											
											if(uid_2_obj!=null){
												final String uid_2_from_server = uid_2_obj.toString();
												if(uid_2_from_server!=null){
													tryConnect(NickName, uid_2_from_server, Pwd,new ConnectCallBack() {
														
														@Override
														public void connectResult(boolean successOrFail) {
															if(successOrFail){
																//success
																dbm.addUidMapping(Uid, uid_2_from_server, 1);
																//update device table
																dbm.updateDevUid(Uid, uid_2_from_server);
																
																resultUID = uid_2_from_server;
																
																goback();
															}else{
																//-----------------------game over-----------------------
																goback();
															}
														}
													});
												}else{
													goback();
												}
											}else{
												goback();
											}
										}
									}
								});
							}else{
								goback();
							}
						}else{
							goback();
						}
					}
				}else if(isBlack == -1){
					Log.i("TenvisUtil", "network prblem (isBlack = -1)");
					goback();
					return;
				}
			}
		}).start();
	}
	

	//尝试连线，确定是否是正确的UID
	private void tryConnect(String name,String uid,String pwd,ConnectCallBack callback){
		MyCamera camera = null;
		camera = new MyCamera(name, uid, "admin", pwd);
		camera.registerIOTCListener(this);
		camera.connect(uid);
		camera.start(Camera.DEFAULT_AV_CHANNEL, "admin", pwd);
		camera.call = callback;
		
		CameraList.add(camera);
	}
	
	interface IGetNewUid {
		void returnNewUid(String newUID);
	}
	
	//从server端获取需要替换的新UID
	private void getNewUidFromServer(final String uid , final IGetNewUid call){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				String newUid = "";
				if(uid!=null && uid.length()==20){
					//uid bytes
					byte[] uidBytes = uid.getBytes();
					//params
					byte[] data = XORUtil.getRandomByteArray();
					data[8]=0x01;
					byte randomKey = XORUtil.getXorKey();
					data[15] = randomKey;
					uidBytes = XORUtil.XorEncrypt(randomKey, uidBytes);
					System.arraycopy(uidBytes, 0, data, 33, 20);
					data[70] = (byte) 0xF0;
					data[71] = (byte) 0x9E;
					
					DefaultHttpClient httpClient =new DefaultHttpClient();
					try {
						String url = "http://tenvis-app.throughtek.cn:7780/api?data="+XORUtil.encoder(data);
						HttpGet httpGet = new HttpGet(url);
						httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
						ResponseHandler<String> responseHandler = new BasicResponseHandler();
						String resp = httpClient.execute(httpGet, responseHandler);
						
						byte[] myresp = XORUtil.decoder(resp);
						
						byte fix1_ckuid= myresp[100];
						byte fix2_ckuid= myresp[101];
						if(fix1_ckuid == (byte)0xA5 && fix2_ckuid == (byte)0xCC){
							byte resCode = myresp[12];
							if(resCode == 0){
								//不在list ， normal UID
								newUid = "-1";
							}else if(resCode == 1){
								//在list中，获取server端新的UID
								byte xorKey = myresp[13];
								byte[] uidArray = new byte[20];
								System.arraycopy(myresp, 21, uidArray, 0, 20);
								uidArray = XORUtil.XorEncrypt(xorKey, uidArray);
								
								newUid = new String(uidArray);
							}else if(resCode == 2){
								newUid = "-1";
								Log.d("AAA","he request UID is in the list but out of update quota");
							}
						}
					} catch (Exception e) {
						newUid="-1";
						httpClient.getConnectionManager().shutdown();
					}finally{
						httpClient.getConnectionManager().shutdown();
					}
				}
				call.returnNewUid(newUid);
			}
		}).start();
		
	}
	
	//判断UID是否在Lan Search List中，确定是否要获取新的UID，以及烧录动作
	private String isInLanSearchList(String uid){
		String ip_address = "";
		list_lan.clear();
		st_LanSearchInfo[] arrResp = Camera.SearchLAN();
		if (arrResp != null && arrResp.length > 0) {
			for (st_LanSearchInfo resp : arrResp) {
				list_lan.add(new SearchResult(new String(resp.UID), new String(resp.IP),resp.port));
			}
		}
		if(list_lan.size()>0){
			for(SearchResult sr : list_lan){
				if(sr!=null && sr.UID.equals(uid)){
					ip_address = sr.IP;
					break;
				}
			}
		}
		return ip_address;
	}
	
	
	//从server端获取mapping记录，根据返回值判断此UID是否在黑名单中
	private Map<String,Object> checkUidInBlackList(String uid){
		Map<String ,Object> map = new HashMap<String,Object>();
		
		if(uid!=null && uid.length()==20){
			//uid bytes
			byte[] uidBytes = uid.getBytes();
			//params
			byte[] data = XORUtil.getRandomByteArray();
			data[5]=0x02;
			byte randomKey = XORUtil.getXorKey();
			data[29] = randomKey;
			uidBytes = XORUtil.XorEncrypt(randomKey, uidBytes);
			System.arraycopy(uidBytes, 0, data, 43, 20);
			data[88] = (byte) 0x70;
			data[89] = (byte) 0x32;
			
			DefaultHttpClient httpClient =new DefaultHttpClient();
			try {
				String url = "http://tenvis-app.throughtek.cn:7780/api?data="+XORUtil.encoder(data);
				HttpGet httpGet = new HttpGet(url);
				httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String resp = httpClient.execute(httpGet, responseHandler);
				byte[] mappingLogArr = XORUtil.decoder(resp);
				
				byte fix1= mappingLogArr[99];
				byte fix2= mappingLogArr[100];
				
				if(fix1 == (byte)0x2A && fix2 == (byte)0x6E){
					//有效数据
					byte resultCode = mappingLogArr[2];
					if(resultCode == 0){
						//说明UID合法
						map.put("isBlack",0);
					}else if(resultCode == 1){
						//get log number
						byte logNum = mappingLogArr[7];
						if(logNum == 0){
							//说明UID不合法，但没有mapping记录
							map.put("isBlack",1);
							map.put("cnt",0);
						}else if(logNum == 1){
							//说明UID不合法，有1条mapping记录
							map.put("isBlack",1);
							map.put("cnt",1);
							
							byte key = mappingLogArr[10];
							//XOR get uid
							byte[] uidArray = new byte[20];
							System.arraycopy(mappingLogArr, 19, uidArray, 0, 20);
							uidArray = XORUtil.XorEncrypt(key, uidArray);
							String uidOne = new String(uidArray);
							
							map.put("uid_1", uidOne);
						}else if(logNum == 2){
							//说明UID不合法，有2条mapping记录
							map.put("isBlack",1);
							map.put("cnt",2);
							
							byte key = mappingLogArr[10];
							//XOR get uid
							byte[] uidArrayOne = new byte[20];
							System.arraycopy(mappingLogArr, 19, uidArrayOne, 0, 20);
							uidArrayOne = XORUtil.XorEncrypt(key, uidArrayOne);
							String uidOne = new String(uidArrayOne);
							
							byte[] uidArrayTwo = new byte[20];
							System.arraycopy(mappingLogArr, 54, uidArrayTwo, 0, 20);
							uidArrayTwo = XORUtil.XorEncrypt(key, uidArrayTwo);
							String uidTwo = new String(uidArrayTwo);
							
							map.put("uid_1", uidOne);
							map.put("uid_2", uidTwo);
						}
					}
				}else{
					map.put("isBlack",-1);//data 无效
				}
			} catch (Exception e) {
				e.printStackTrace();
				map.put("isBlack",-1);//data 无效
				httpClient.getConnectionManager().shutdown();
			}finally{
				httpClient.getConnectionManager().shutdown();
			}
		}else{
			map.put("isBlack",-1);//data 无效
		}
		
		return map;
	}
	
	//http function
	private String doHttpReq(String url){
		DefaultHttpClient httpClient =new DefaultHttpClient();
		String response2 ="";
		try {
			byte[] encodedPassword = (NAME + ":" + PASSWORD).getBytes();  
			
		    HttpGet httpGet = new HttpGet(url);
		    httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
		    httpGet.setHeader("Authorization","Basic "+Base64.encodeToString(encodedPassword, Base64.NO_WRAP));
		    ResponseHandler<String> responseHandler = new BasicResponseHandler();
			
		    response2 = httpClient.execute(httpGet, responseHandler);
		} catch (Exception e) {
			httpClient.getConnectionManager().shutdown();
			return "-1";
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
		return response2;
	}
	/**
	 * 烧录UID
	 */
	private void burningUidForDevice(final String ip ,final int port, String uid , String newUid){
		//A-------------烧录new UID到dev，调用CGI接口-------------
		String url =  buildOne(ip,newUid);
		//set new UID for dev
		String res = doHttpReq(url);
		if("-1".equals(res)){
			Log.d("AAA","doHttpReq res : -1＝＝＝＝not this custorm 's dev");
		}else{
			if(res!=null && !"".equals(res) && (res.contains("Succe") || res.contains("succe") || res.contains("ok") || res.contains("OK") || res.contains("Ok"))){
				//记录本地mapping
				dbm.addUidMapping(uid, newUid,0);
				//update device table
				dbm.updateDevUid(uid, newUid);
				Log.d("AAA","烧录UID成功："+res);
				
				resultUID = newUid;
				
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						//烧录UID成功，reboot dev
						String url_reboot = "http://"+ip+"/cgi-bin/hi3510/sysreboot.cgi";
						String reboot_res = doHttpReq(url_reboot);
						Log.d("AAA","reboot mesg ："+reboot_res);
					}
				}).start();
			}else{
				Log.d("AAA","烧录UID失败："+res);
				//TODO 是否再次烧录
			}
		}
		
		//B-------------烧录new UID到dev，调用CGI接口-------------
		url = buildOne2(ip, port, newUid);
		res = doHttpReq(url);
		if("-1".equals(res)){
			Log.d("AAA","doHttpReq res : -1＝＝＝＝not this custorm 's dev");
		}else{
			if(res!=null && !"".equals(res) && (res.contains("Succe") || res.contains("succe") || res.contains("ok") || res.contains("OK") || res.contains("Ok"))){
				//记录本地mapping
				dbm.addUidMapping(uid, newUid,0);
				//update device table
				dbm.updateDevUid(uid, newUid);
				
				resultUID = newUid;
				Log.d("AAA","烧录UID成功："+res);
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						//烧录UID成功，reboot dev
						String url_reboot = "http://"+ip+":"+port+"/cgi-bin/hi3510/sysreboot.cgi&-usr="+NAME+"&-pwd="+PASSWORD;
						String reboot_res = doHttpReq(url_reboot);
						Log.d("AAA","reboot mesg ："+reboot_res);
					}
				}).start();
				
			}else{
				Log.d("AAA","烧录UID失败："+res);
				//TODO 是否再次烧录
			}
		}
		
		//C-------------烧录new UID到dev，调用CGI接口-------------
		url = buildTwo(ip, port, newUid);
		res = doHttpReq(url);
		if("-1".equals(res)){
			Log.d("AAA","doHttpReq res : -1＝＝＝＝not this custorm 's dev");
		}else{
			if(res!=null && !"".equals(res) && (res.contains("Succe") || res.contains("succe") || res.contains("ok") || res.contains("OK") || res.contains("Ok"))){
				//记录本地mapping
				dbm.addUidMapping(uid, newUid,0);
				//update device table
				dbm.updateDevUid(uid, newUid);
				
				resultUID = newUid;
				
				Log.d("AAA","烧录UID成功："+res);
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						//烧录UID成功，reboot dev
						String url_reboot = "http://"+ip+":"+port+"/cgi-bin/control.cgi?action=cmd&code=255&value=255&user="+NAME+"&pwd="+PASSWORD;
						String reboot_res = doHttpReq(url_reboot);
						Log.d("AAA","reboot mesg ："+reboot_res);
					}
				}).start();
				
				
			}else{
				Log.d("AAA","烧录UID失败："+res);
				//TODO 是否再次烧录
			}
		}
		
		
		//C 2-------------烧录new UID到dev，调用CGI接口-------------
		final int prot_7777 = 7777;
		url = buildTwo(ip, prot_7777, newUid);
		res = doHttpReq(url);
		if("-1".equals(res)){
			Log.d("AAA","doHttpReq res : -1＝＝＝＝not this custorm 's dev");
		}else{
			if(res!=null && !"".equals(res) && (res.contains("Succe") || res.contains("succe") || res.contains("ok") || res.contains("OK") || res.contains("Ok"))){
				//记录本地mapping
				dbm.addUidMapping(uid, newUid,0);
				//update device table
				dbm.updateDevUid(uid, newUid);
				
				resultUID = newUid;
				
				Log.d("AAA","烧录UID成功："+res);
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						//烧录UID成功，reboot dev
						String url_reboot = "http://"+ip+":"+prot_7777+"/cgi-bin/control.cgi?action=cmd&code=255&value=255&user="+NAME+"&pwd="+PASSWORD;
						String reboot_res = doHttpReq(url_reboot);
						Log.d("AAA","reboot mesg ："+reboot_res);
					}
				}).start();
			}else{
				Log.d("AAA","烧录UID失败："+res);
				//TODO 是否再次烧录
			}
		}
		
		
		//D-------------烧录new UID到dev，调用CGI接口-------------
		url = buildThree(ip, port, newUid);
		res = doHttpReq(url);
		String uuu = getUidForThreeURL(ip,port);
		res = doHttpReq(uuu);
		if(res!=null && !"".equals(res) && res.contains(newUid)){
			//记录本地mapping
			dbm.addUidMapping(uid, newUid,0);
			//update device table
			dbm.updateDevUid(uid, newUid);
			
			resultUID = newUid;
			
			Log.d("AAA","烧录UID成功："+res);
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					//烧录UID成功，reboot dev
					String url_reboot = "http://"+ip+":"+port+"/cgi-bin/hi3510/reboot.cgi";
					String reboot_res = doHttpReq(url_reboot);
					Log.d("AAA","reboot mesg ："+reboot_res);
				}
			}).start();
			
		}
	}
	
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			String requestDevice = bundle.getString("requestDevice");
			MyCamera camera = null;
			ConnectCallBack callback = null;

			for (int i = 0; i < CameraList.size(); i++) {
				if (CameraList.get(i).getUUID().equalsIgnoreCase(requestDevice)) {
					camera = CameraList.get(i);
					callback = camera.call;
					break;
				}
			}
			
			switch (msg.what) {
				case Camera.CONNECTION_STATE_CONNECTED:
					camera.unregisterIOTCListener(TenvisUtil.this);
					camera.disconnect();
					
					if(callback!=null){
						callback.connectResult(true);
						callback = null;
						camera.call = null;
					}
					break;
				case Camera.CONNECTION_STATE_CONNECTING:
					break;
				case Camera.CONNECTION_STATE_UNKNOWN_DEVICE:
				case Camera.CONNECTION_STATE_DISCONNECTED:
				case Camera.CONNECTION_STATE_TIMEOUT:
				case Camera.CONNECTION_STATE_WRONG_PASSWORD:
				case Camera.CONNECTION_STATE_CONNECT_FAILED:
					camera.unregisterIOTCListener(TenvisUtil.this);
					camera.disconnect();
					
					if(callback!=null){
						callback.connectResult(false);
						callback = null;
						camera.call = null;
					}
					break;
			}
		};
	};

	@Override
	public void receiveSessionInfo(final Camera camera, int resultCode) {
		Bundle bundle = new Bundle();
		bundle.putString("requestDevice", ((MyCamera) camera).getUUID());

		Message msg = handler.obtainMessage();
		msg.what = resultCode;
		msg.setData(bundle);
		handler.sendMessage(msg);
	}

	@Override
	public void receiveChannelInfo(final Camera camera, int sessionChannel, int resultCode) {
		Bundle bundle = new Bundle();
		bundle.putString("requestDevice", ((MyCamera) camera).getUUID());
		bundle.putInt("sessionChannel", sessionChannel);

		Message msg = handler.obtainMessage();
		msg.what = resultCode;
		msg.setData(bundle);
		handler.sendMessage(msg);
	}

	@Override
	public void receiveIOCtrlData(final Camera camera, int sessionChannel, int avIOCtrlMsgType, byte[] data) {
		Bundle bundle = new Bundle();
		bundle.putString("requestDevice", ((MyCamera) camera).getUUID());
		bundle.putInt("sessionChannel", sessionChannel);
		bundle.putByteArray("data", data);

		Message msg = handler.obtainMessage();
		msg.what = avIOCtrlMsgType;
		msg.setData(bundle);
		handler.sendMessage(msg);
	}
	
	@Override
	public void receiveFrameDataForMediaCodec(Camera camera, int avChannel,
											  byte[] buf, int length, int pFrmNo, byte[] pFrmInfoBuf,
											  boolean isIframe, int codecId) {
	}
	
	@Override
	public void receiveFrameData(final Camera camera, int sessionChannel, Bitmap bmp) {
	}

	@Override
	public void receiveFrameInfo(final Camera camera, int sessionChannel, long bitRate, int frameRate, int onlineNm, int frameCount, int incompleteFrameCount) {
	}
	
	
	private String buildOne(String ip,String newUid){
		String temp=
				"http://"
				+ ip
				+ "/cgi-bin/hi3510/param.cgi?cmd=setp2pattr&-p2p_enable=1&-p2p_uid="
				+ newUid
				+ "&-p2p_fullfunc=1&-p2p_server1=50.19.254.134&-p2p_server2=122.248.234.207&-p2p_server3=m2.iotcplatform.com&-p2p_server4=m5.iotcplatform.com";
		return temp;
	}
	
	
	private String buildOne2(String ip,int port,String newUid){
		String temp=
				"http://"
				+ ip
				+ ":"
				+ port
				+ "/cgi-bin/hi3510/param.cgi?cmd=setp2pattr&-p2p_enable=1&-p2p_fullfunc=1&-p2p_uid="
				+ newUid
				+ "&-p2p_server1=50.19.254.134&-p2p_server2=122.248.234.207&-p2p_server3=m2.iotcplatform.com&-p2p_server4=m5.iotcplatform.com&-usr="
				+ NAME + "&-pwd=" + PASSWORD;
		return temp;
	}
	
	private String buildTwo(String ip,int port ,String newUid){
		String temp="http://"+ip+":"+port+"/p2p.cgi?uid="+newUid+"&user="+NAME+"&pwd="+PASSWORD;
		return temp;
	}
	
	
	
	private String buildThree(String ip,int port ,String newUid){
		String temp=
		"http://"+ip+":"+port+"/cgi-bin/factory_tvs.cgi?cmd=factory_tvs.cgi&-action=set&-p2p_enable=1&-p2p_tran=tutk_tran&-p2p_pwd="+PASSWORD+"&-p2p_uid="+newUid;
		return temp;
	}
	
	private String getUidForThreeURL(String ip,int port){
		return "http://"+ip+":"+port+"/cgi-bin/factory_tvs.cgi?cmd=factory_tvs.cgi&-action=get";
	}
	
	
	private class SearchResult {
		public String UID;
		public String IP;
		public int PORT;
		public SearchResult(String uid, String ip,int p) {
			UID = uid;
			IP = ip;
			PORT = p;
		}
	}
}
